<?php

/**
 * ECSHOP 管理中心版本管理
 * ============================================================================
 */
 
define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');

/*------------------------------------------------------ */
//-- 活动列表页
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
    admin_priv('users_manage');


    /* 模板赋值 */
    $smarty->assign('full_page',   1);
    $smarty->assign('ur_here',     '版本列表');
    $smarty->assign('action_link', array('href' => 'apk_version.php?act=add', 'text' => '添加版本'));

    $list = apk_version_list();
// print_r($list);exit;

    $smarty->assign('apk_version_list', $list['item']);
    $smarty->assign('filter',          $list['filter']);
    $smarty->assign('record_count',    $list['record_count']);
    $smarty->assign('page_count',      $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);



    /* 显示商品列表页面 */
    assign_query_info();
    $smarty->display('apk_version_list.htm');
}


/*------------------------------------------------------ */
//-- 分页、排序、查询
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'query')
{
    $list = apk_version_list();

    $smarty->assign('apk_version_list', $list['item']);
    $smarty->assign('filter',          $list['filter']);
    $smarty->assign('record_count',    $list['record_count']);
    $smarty->assign('page_count',      $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);


    make_json_result($smarty->fetch('apk_version_list.htm'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));
}

/*------------------------------------------------------ */
//-- 删除
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('users_manage');

    $id = intval($_GET['id']);
    $apk_version = apk_version_info($id);

    if (empty($apk_version))
    {
        make_json_error($_LANG['favourable_not_exist']);
    }
    $name = $apk_version['user_name'];


    $sql=" delete from ".$GLOBALS['ecs']->table('apk_version')." where apk_version_id=".$id;
  
    $status=$GLOBALS['db']->query($sql);


    /* 记日志 */
    admin_log('删除'.$apk_version['user_name'].'的版本'.$id, 'remove', 'apk_version');

    /* 清除缓存 */
    clear_cache_files();

    $url = 'apk_version.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);
    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch')
{

    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']))
    {
        sys_msg($_LANG['no_record_selected']);
    }
    else
    {
        /* 检查权限 */
        admin_priv('users_manage');


        $ids = $_POST['checkboxes'];
        if (isset($_POST['drop']))
        {
           

            /* 删除记录 */


            /* 记日志 */
            admin_log('', 'batch_remove', 'apk_version');

            /* 清除缓存 */
            clear_cache_files();

            $links[] = array('text' => '返回版本列表', 'href' => 'apk_version.php?act=list&' . list_link_postfix());
            sys_msg($_LANG['batch_drop_ok']);
        }
      
    }
}


/*------------------------------------------------------ */
//-- 添加、编辑
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('users_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add';
    $smarty->assign('form_action', $is_add ? 'insert' : 'update');


    /* 初始化、取得优惠活动信息 */
    if ($is_add)
    {
        // $sql = 'SELECT c.cat_id,c.cat_name ' .
        //         ' FROM ' . $GLOBALS['ecs']->table('category') . ' as c ' .
        //         'left join ' . $GLOBALS['ecs']->table('touch_category') . ' as t on t.cat_id = c.cat_id ' .
        //         "WHERE c.parent_id = 0 AND c.is_show = 1 ORDER BY c.sort_order ASC, c.cat_id ASC";
        // $cats =$GLOBALS['db']->getAll($sql);

        $apk_version = array(
            'apk_version_id'        => 0,
            'apk_version_name'        =>'',
             'apk_version_url'        => '',
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }
        $id = intval($_GET['id']);
        $apk_version = apk_version_info($id);
        if (empty($apk_version))
        {
            sys_msg($_LANG['favourable_not_exist']);
        }

    }
    $smarty->assign('apk_version', $apk_version);


    // print_r($apk_version);exit();


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', $_LANG['add_favourable']);
    }
    else
    {
        $smarty->assign('ur_here', $_LANG['edit_favourable']);
    }
    $href = 'apk_version.php?act=list';
    if (!$is_add)
    {
        $href .= '&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => $_LANG['favourable_list']));
    assign_query_info();
    $smarty->display('apk_version_info.htm');
}

/*------------------------------------------------------ */
//-- 添加、编辑后提交
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('users_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';

    /* 检查版本是否重复 */
    $id=intval($_POST['id'])?intval($_POST['id']):0;
    $version = $_POST['version']? $_POST['version'] : '0';
    $apk_version_name = $_POST['apk_version_name']? $_POST['apk_version_name'] : 'XXXX';
    // $apk_version_url = intval($_POST['apk_version_url'])? $_POST['apk_version_url'] : '';
    $sort_order =  intval($_POST['sort_order'])? $_POST['sort_order'] : '';




    if($_FILES['apk_version_url']["tmp_name"])
    {
        $status=move_uploaded_file($_FILES["apk_version_url"]["tmp_name"],"../app_api/apk/".$version."_" .$_FILES["apk_version_url"]["name"]);
        if(!$status){sys_msg('文件上传失败');}  
         $apk_version_url="app_api/apk/".$version."_".$_FILES["apk_version_url"]["name"];

    }
    else
    {
        $apk_version_url=$_POST['old_apk_version_url']? $_POST['old_apk_version_url'] : '';
    }
 


    

    /* 提交值 */
    $apk_version = array(
        'apk_version_id'        => intval($_POST['id']),
        'version'        => $version,
        'apk_version_name'        =>$apk_version_name,
        'apk_version_url'        => $apk_version_url
    );

    /* 保存数据 */
    if ($is_add)
    {
        if(!$_FILES['apk_version_url']){sys_msg('文件上传为空');}
        //最新apk
        copy("../app_api/apk/".$version."_" .$_FILES["apk_version_url"]["name"],"../app_api/JXTD.apk");

        $now_time=gmtime();
        $apk_version['ctime']=$now_time;

        $db->autoExecute($ecs->table('apk_version'), $apk_version, 'INSERT');
        $apk_version['apk_version_id'] = $db->insert_id();
         
    }
    else
    {
        $sql="select count(*) as num from  ".$GLOBALS['ecs']->table('apk_version')." where apk_version_id>$id ";
        $num=$GLOBALS['db']->getOne($sql);
        //最新apk
        if($num<1) copy("../app_api/apk/".$version."_" .$_FILES["apk_version_url"]["name"],"../app_api/JXTD.apk");


        $db->autoExecute($ecs->table('apk_version'), $apk_version, 'UPDATE', "apk_version_id = '$apk_version[apk_version_id]'");
         
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log('添加版本'.$apk_version['apk_version_id'], 'add', 'apk_version');
    }
    else
    {
        admin_log('编辑版本'.$apk_version['apk_version_id'], 'edit', 'apk_version');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'apk_version.php?act=add', 'text' => $_LANG['continue_add_favourable']),
            array('href' => 'apk_version.php?act=list', 'text' => $_LANG['back_favourable_list'])
        );
        sys_msg($_LANG['add_favourable_ok'], 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'apk_version.php?act=list&' . list_link_postfix(), 'text' => $_LANG['back_favourable_list'])
        );
        sys_msg($_LANG['edit_favourable_ok'], 0, $links);
    }
}
/*------------------------------------------------------ */
//-- 搜索商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'search')
{
    /* 检查权限 */
    check_authz_json('apk_version');

    include_once(ROOT_PATH . 'includes/cls_json.php');

    $json   = new JSON;
    $filter = $json->decode($_GET['JSON']);
    $filter->keyword = json_str_iconv($filter->keyword);
    if ($filter->act_range == FAR_ALL)
    {
        $arr[0] = array(
            'id'   => 0,
            'name' => $_LANG['js_languages']['all_need_not_search']
        );
    }
    else
    {
       $arr=$apk_version_list;
    }

    if (empty($arr))
    {
        $arr = array(0 => array(
            'id'   => 0,
            'name' => $_LANG['search_result_empty']
        ));
    }

    make_json_result($arr);
}

/*
 * 取得版本列表
 * @return   array
 */
function apk_version_list()
{    
    $result = get_filter();
    if ($result === false)
    {
        /* 过滤条件 */
        $filter['version']    = empty($_REQUEST['version']) ? '' : trim($_REQUEST['version']); 
        $filter['keyword']    = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);  

        

        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['version'] = json_str_iconv($filter['version']);
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }

        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'm.apk_version_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = "";
        if (!empty($filter['version']))
        {
            $where .= " AND m.version LIKE '%" . mysql_like_quote($filter['version']). "%'";
        }
        if (!empty($filter['keyword']))
        {
            $where .= " AND m.apk_version_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
        }


       


      $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('apk_version') ." as m  ".
        " WHERE 1 $where";
       $filter['record_count'] = $GLOBALS['db']->getOne($sql);



     /* 分页大小 */
        $filter = page_and_size($filter);

        /* 查询 */
        $sql = "SELECT m.*".
                " FROM " . $GLOBALS['ecs']->table('apk_version')." as m  ".
                " WHERE 1 $where ".
                " ORDER BY $filter[sort_by] $filter[sort_order] ".
                " LIMIT ". $filter['start'] .", $filter[page_size]";
      
        $filter['keyword'] = stripslashes($filter['keyword']);


        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->query($sql);





    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['ctime']=local_date('Y-m-d H:i:s',$row['ctime']);
        $row['avn_url']="http://".$_SERVER["HTTP_HOST"]."/".$row['apk_version_url'];

        $list[] = $row;
    }

    return array('item' => $list, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

   function apk_version_info($id)
   {
        $sql="SELECT m.* ".
                "FROM " . $GLOBALS['ecs']->table('apk_version')." as m  ".
                " where m.apk_version_id=".$id;
        $row=$GLOBALS['db']->getRow($sql);

        $row['avn_url']="http://".$_SERVER["HTTP_HOST"]."/".$row['apk_version_url'];
 
        return $row;
   }

   //随机数
    function nb_random($length = 6, $numeric = 0) {
        PHP_VERSION < '4.2.0' && mt_srand((double) microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    } 
   
   
?>